package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.powernode.mapper.SysUserMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysUser> getSysUserPage(Page<SysUser> page, SysUser sysUser) {
        Page<SysUser> userPage = sysUserMapper.selectPage(page, new LambdaQueryWrapper<SysUser>()
                //进行模糊查询 如果 没传入值则全部查询
                .like(StringUtils.hasText(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername()));
        return userPage;
    }

    @Override
    @Transactional
    public void addUserAndRole(SysUser sysUser) {
        //插入sysUser
        sysUser.setCreateTime(new Date());
        sysUserMapper.insert(sysUser);
        List<Long> roleIdList = sysUser.getRoleIdList();
        //得到所有的id 并封装到sysUserRole中间表
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        roleIdList.forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRoles.add(sysUserRole);
        });
        //通过id添加角色
        sysUserRoleService.saveBatch(sysUserRoles);
    }
}




